import { defineComponent, ref, computed } from 'vue';
import {
  format,
  startOfMonth,
  endOfMonth,
  eachDayOfInterval,
  isSameMonth,
  isSameDay,
} from 'date-fns';
import { reminderDB ,type Reminder} from '@/utils/ReminderDb';

const Calendar = defineComponent({
  name: 'Calendar',
  setup() {
    const currentDate = ref(new Date());
    const reminders = ref<Reminder[]>([]);
    const selectedDate = ref<Date | null>(null);
    const isModalOpen = ref(false);
    const reminderContent = ref('');

    const monthDays = computed(() => {
      return eachDayOfInterval({
        start: startOfMonth(currentDate.value),
        end: endOfMonth(currentDate.value),
      });
    });

    const handleDateClick = (date: Date) => {
      selectedDate.value = date;
      isModalOpen.value = true;
    };

    const handleAddReminder = async () => {
      if (selectedDate.value && reminderContent.value.trim()) {
        reminders.value.push({
          date: selectedDate.value,
          content: reminderContent.value,
        });
        await reminderDB.addReminder({
            date: selectedDate.value,
            content: reminderContent.value
        })
        reminderContent.value = '';
        isModalOpen.value = false;
      }
    };

    const prevMonth = () => {
      currentDate.value = new Date(currentDate.value.setMonth(currentDate.value.getMonth() - 1));
    };

    const nextMonth = () => {
      currentDate.value = new Date(currentDate.value.setMonth(currentDate.value.getMonth() + 1));
    };

    const goToToday = () => {
      currentDate.value = new Date();
    };

    return () => (
      <div class="max-w-4xl mx-auto p-5 h-full">
        <div class="flex justify-between items-center mb-5">
          <h2 class="text-2xl font-semibold">
            {format(currentDate.value, 'yyyy年 MM月')}
          </h2>
          <div class="space-x-2">
            <button 
              onClick={prevMonth}
              class="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
            >
              上个月
            </button>
            <button 
              onClick={goToToday}
              class="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
            >
              今天
            </button>
            <button 
              onClick={nextMonth}
              class="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
            >
              下个月
            </button>
          </div>
        </div>

        <div class="grid grid-cols-7 gap-px h-[20rem]">
          {['日', '一', '二', '三', '四', '五', '六'].map((day) => (
            <div key={day} class="bg-gray-50 p-3 text-center font-medium">
              {day}
            </div>
          ))}
          {monthDays.value.map((day) => (
            <div
              key={day.toISOString()}
              class={`
                bg-white p-3 cursor-pointer relative hover:bg-gray-50 transition-colors flex justify-center items-center
                ${!isSameMonth(day, currentDate.value) ? 'text-blue-50' : ''}
                ${isSameDay(day, new Date()) ? 'bg-blue-50' : ''}
              `}
              onClick={() => handleDateClick(day)}
            >
              <span>{format(day, 'd')}</span>
              {reminders.value.some((reminder) => isSameDay(reminder.date, day)) && (
                <div class="absolute bottom-2 right-2 w-2 h-2 bg-blue-500 rounded-full" />
              )}
            </div>
          ))}
        </div>

        {isModalOpen.value && (
          <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
            <div class="bg-white rounded-lg p-6 w-[400px]">
              <h3 class="text-lg font-semibold mb-4">
                {format(selectedDate.value!, 'yyyy年MM月dd日')} 添加提醒
              </h3>
              <textarea
                v-model={reminderContent.value}
                placeholder="请输入提醒内容"
                class="w-full h-32 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              />
              <div class="flex justify-end space-x-2 mt-4">
                <button 
                  onClick={() => isModalOpen.value = false}
                  class="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
                >
                  取消
                </button>
                <button 
                  onClick={handleAddReminder}
                  class="px-4 py-2 bg-blue-500 text-white hover:bg-blue-600 rounded-md transition-colors"
                >
                  保存
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  },
});

export default Calendar;